window.onload = function () {
  // 获取元素
  const links = document.querySelectorAll(".nav li a");

  // 监听点击
  links.forEach(item => item.onclick = e => document.title = e.target.dataset.title)

  // 获取资源
  const getResources = type => {
    $.ajax({
      url: `../html/${type}.html`,
      type: "get",
      success: res => {
        $(res).each((_, item) => {
          // 处理 html
          if ($(item).is('div') && item.id === "wj-warp") {
            $('#app').html($(item))
          }
          
          // 处理 js
          $(item).is('script') && item.src && import(item.src + "?" + new Date().getTime());

          // 处理 css
          if ($(item).is('link') && item.href && !Array.from($('head').find("link")).filter(x => x.href === item.href).length) {
            const link = document.createElement('link');
            link.href = item.href;
            link.rel = 'stylesheet';
            link.type = 'text/css';
            $('head')[0].appendChild(link);
          }

        })

      }
    })
  }

  // 路由变化
  const hashChange = () => {
    switch (location.hash) {
      case "#/home":
      case "":
        document.title = "首页";
        getResources("home");
        break;
      case "#/about":
        document.title = "关于";
        getResources("about");
        break;
      case "#/card":
        document.title = "购物车";
        getResources("card");
        break;
      case "#/profile":
        document.title = "个人中心";
        getResources("profile");
        break;
      default:
        console.log("路由错误");
        getResources("error");
    }
  }

  // 监听路由
  window.onhashchange = function () {
    hashChange();
  }

  hashChange()
}